﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.Personalization.VisitorGroups;
using System.Text.RegularExpressions;
using EPiServer;

namespace CriteriaPack.BandwidthCriterion
{
    [VisitorGroupCriterion(Category = "Bandwidth Criteria", DisplayName = "Bandwidth", Description = "Being able to test a users bandwidth")]
    public class BandwidthCriteria : CriterionBase<SettingsForBandwidth>
    {

        public override bool IsMatch(System.Security.Principal.IPrincipal principal, HttpContextBase httpContext)
        {
            string cookieval = String.Empty;
            try
            {
                cookieval = HttpContext.Current.Request.Cookies["bandwidth"].Value;
            }
            catch { }

            if (!string.IsNullOrEmpty(cookieval))
            {

                string tmp = cookieval.Remove(0, 10);
                tmp = tmp.Remove(tmp.Length - 2);
                int bandwidthFromConnection = Convert.ToInt32(tmp);

                string valueForController = Model.Bandwidth;
                int bandwidthFromUser = Convert.ToInt32(valueForController);

                if (bandwidthFromUser == 384)
                {
                    if (bandwidthFromConnection < 384)
                    {
                        return true;
                    }
                }
                else if (bandwidthFromUser == 3000)
                {
                    if (bandwidthFromConnection > 384 && bandwidthFromConnection < 3000)
                    {
                        return true;
                    }
                }
                else if (bandwidthFromUser == 6000)
                {
                    if (bandwidthFromConnection > 3000 && bandwidthFromConnection < 6000)
                    {
                        return true;
                    }
                }
                else if (bandwidthFromUser == 10000)
                {
                    if (bandwidthFromConnection > 6000 && bandwidthFromConnection < 10000)
                    {
                        return true;
                    }
                }
                else if (bandwidthFromUser == 100000)
                {
                    if (bandwidthFromConnection > 10000 && bandwidthFromConnection < 100000)
                    {
                        return true;
                    }
                }
            }
            else
            {
                PageBase page = httpContext.CurrentHandler as PageBase;
                httpContext.Response.Redirect("/Modules/BandWidthCriterion/TestBandWidth.aspx?url=" + page.CurrentPage.LinkURL);
            }

            return false;

        }
    }
}